package org.example.project_12.controller;

import jakarta.servlet.http.HttpSession;
import org.example.project_12.dto.LoginDto;
import org.example.project_12.dto.RegisterDto;
import org.example.project_12.dto.UpdateUserDto;
import org.example.project_12.dto.UserDto;
import org.example.project_12.entity.Space;
import org.example.project_12.entity.User;
import org.example.project_12.service.SpaceService;
import org.example.project_12.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.example.project_12.dto.FavoriteDisplayDto;
import org.example.project_12.entity.Favorite;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private org.example.project_12.service.DocumentService documentService;

    @Autowired
    private org.example.project_12.mapper.FavoriteMapper favoriteMapper;

    // 登录页面
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    // 登录处理
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        Model model,
                        HttpSession session) {
        LoginDto loginDto = new LoginDto();
        loginDto.setUsername(username);
        loginDto.setPassword(password);
        String token = userService.login(loginDto);
        User user = null;
        if (token != null) {
            user = userService.validateToken(token);
        }
        if (user != null) {
            session.setAttribute("user", user);
            if ("ADMIN".equals(user.getRole())) {
                return "redirect:/user/admin";
            }
            return "redirect:/user/space";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    // 注册页面
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    // 注册处理
    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email,
                           Model model) {
        RegisterDto registerDto = new RegisterDto();
        registerDto.setUsername(username);
        registerDto.setPassword(password);
        registerDto.setEmail(email);
        try {
            userService.register(registerDto);
            model.addAttribute("msg", "注册成功，请登录");
            return "login";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "register";
        }
    }

    // 个人空间首页（空间列表）
    @GetMapping("/space")
    public String userSpace(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        java.util.List<org.example.project_12.dto.SpaceDto> spaces = spaceService.getSpacesByOwnerId(user.getId());
        model.addAttribute("spaces", spaces);
        model.addAttribute("type", "owned");
        model.addAttribute("contentPage", "spaceList.jsp");
        model.addAttribute("activePage", "space");
        return "userLayout";
    }

    // 我的文档
    @GetMapping("/docs")
    public String userDocs(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        java.util.List<org.example.project_12.dto.DocumentDto> docs = documentService.getDocumentsByAuthor(user.getId(), user.getId());
        model.addAttribute("docs", docs);
        model.addAttribute("contentPage", "userDocs.jsp");
        model.addAttribute("activePage", "docs");
        return "userLayout";
    }

    // 我的收藏
    @GetMapping("/favorites")
    public String userFavorites(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        java.util.List<Favorite> favorites = favoriteMapper.selectByUserId(user.getId());
        java.util.List<FavoriteDisplayDto> favoriteDtos = new java.util.ArrayList<>();
        for (Favorite fav : favorites) {
            org.example.project_12.dto.DocumentDto docDto = documentService.getDocumentById(fav.getDocumentId(), user.getId());
            if (docDto != null) {
                FavoriteDisplayDto dto = new FavoriteDisplayDto();
                dto.setDocument(docDto);
                dto.setFavoritedAt(fav.getCreatedAt());
                favoriteDtos.add(dto);
            }
        }
        model.addAttribute("favorites", favoriteDtos);
        model.addAttribute("contentPage", "userFavorites.jsp");
        model.addAttribute("activePage", "favorites");
        return "userLayout";
    }

    // 个人资料
    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        model.addAttribute("contentPage", "profile.jsp");
        model.addAttribute("activePage", "profile");
        return "userLayout";
    }

    // 个人资料修改处理
    @PostMapping("/profile")
    public String updateProfile(@RequestParam String email,
                                HttpSession session,
                                Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        UpdateUserDto updateUserDto = new UpdateUserDto();
        updateUserDto.setUsername(user.getUsername());
        updateUserDto.setEmail(email);
        boolean result = userService.updateUserInfo(user.getId(), updateUserDto);
        if (result) {
            user.setEmail(email);
            session.setAttribute("user", user);
            model.addAttribute("user", user);
            model.addAttribute("msg", "信息更新成功");
        } else {
            model.addAttribute("user", user);
            model.addAttribute("error", "信息更新失败");
        }
        model.addAttribute("contentPage", "profile.jsp");
        model.addAttribute("activePage", "profile");
        return "userLayout";
    }

    // 修改密码页面
    @GetMapping("/changePassword")
    public String changePasswordPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        return "changePassword";
    }

    // 修改密码处理
    @PostMapping("/changePassword")
    public String changePassword(@RequestParam String oldPassword,
                                 @RequestParam String newPassword,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        boolean result = userService.changePassword(user.getId(), oldPassword, newPassword);
        if (result) {
            model.addAttribute("msg", "密码修改成功");
        } else {
            model.addAttribute("error", "密码修改失败");
        }
        return "changePassword";
    }

    // 注销登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login";
    }

    // 管理员用户列表
    @GetMapping("/list")
    public String userList(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        List<UserDto> userList = userService.getUserList(null, null);
        model.addAttribute("userList", userList);
        return "userList";
    }

    // 管理员审核用户
    @PostMapping("/approve")
    public String approveUser(@RequestParam Long userId,
                              @RequestParam String status,
                              HttpSession session,
                              Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        boolean result = userService.approveUser(userId, status);
        if (result) {
            model.addAttribute("msg", "操作成功");
        } else {
            model.addAttribute("error", "操作失败");
        }
        List<UserDto> userList = userService.getUserList(null, null);
        model.addAttribute("userList", userList);
        return "userList";
    }

    // 管理员禁用/启用用户
    @PostMapping("/toggle-status")
    public String toggleUserStatus(@RequestParam Long userId,
                                   @RequestParam String status,
                                   HttpSession session,
                                   Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        boolean result = userService.toggleUserStatus(userId, status);
        if (result) {
            model.addAttribute("msg", "操作成功");
        } else {
            model.addAttribute("error", "操作失败");
        }
        List<UserDto> userList = userService.getUserList(null, null);
        model.addAttribute("userList", userList);
        return "userList";
    }

    // 我的评论
    @GetMapping("/comments")
    public String userComments(HttpSession session, Model model, @Autowired org.example.project_12.service.CommentService commentService) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        java.util.List<org.example.project_12.entity.Comment> comments = commentService.getCommentsByUser(user.getId());
        // 按文档分组
        java.util.Map<Long, java.util.List<java.util.Map<String, Object>>> commentGroups = new java.util.LinkedHashMap<>();
        for (org.example.project_12.entity.Comment c : comments) {
            org.example.project_12.dto.DocumentDto doc = documentService.getDocumentById(c.getDocId(), user.getId());
            java.util.Map<String, Object> commentMap = new java.util.HashMap<>();
            commentMap.put("content", c.getContent());
            commentMap.put("createdAt", c.getCreatedAt());
            commentMap.put("docId", c.getDocId());
            commentMap.put("docTitle", doc != null ? doc.getTitle() : "");
            commentGroups.computeIfAbsent(c.getDocId(), k -> new java.util.ArrayList<>()).add(commentMap);
        }
        model.addAttribute("commentGroups", commentGroups);
        model.addAttribute("contentPage", "userComments.jsp");
        model.addAttribute("activePage", "comments");
        return "userLayout";
    }

    // 管理员文档管理页面
    @GetMapping("/admin/docs")
    public String adminDocs(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        java.util.List<org.example.project_12.dto.DocumentDto> pendingDocs = documentService.getDocumentsByStatus("PENDING");
        java.util.List<org.example.project_12.dto.DocumentDto> publicDocs = documentService.getDocumentsByStatus("PUBLIC");
        model.addAttribute("pendingDocs", pendingDocs);
        model.addAttribute("publicDocs", publicDocs);
        model.addAttribute("contentPage", "adminDocs.jsp");
        model.addAttribute("activePage", "adminDocs");
        return "userLayout";
    }
    // 审核通过
    @PostMapping("/admin/docs/approve/{docId}")
    public String approveDoc(@PathVariable Long docId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        documentService.updateDocumentStatus(docId, "PUBLIC");
        return "redirect:/user/admin/docs";
    }
    // 驳回/设为私有
    @PostMapping("/admin/docs/reject/{docId}")
    public String rejectDoc(@PathVariable Long docId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        documentService.updateDocumentStatus(docId, "PRIVATE");
        return "redirect:/user/admin/docs";
    }

    @GetMapping("/admin")
    public String adminPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null || !"ADMIN".equals(user.getRole())) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        return "admin";
    }
} 